import os,time,md5
class FileDiffListener:
    def __init__(self, f_path):
        self.f_path = f_path
        self.digest = ''
        self.digest_new = ''
        self.mtime = 0
        self.mtime_new = 0
        self.isChanged = False

    def isDiff(self):
        if self.digest=='' or self.mtime==0:
            self.saveDiff()
        elif not self.isChanged:
            self.mtime_new = self.getMTime()
            if self.mtime!=self.mtime_new :
                self.digest_new = self.genDigest()
                self.isChanged = (self.digest_new!=self.digest)
        return self.isChanged

    def saveDiff(self):
        if self.digest_new=='' or self.mtime==0:
            self.digest_new = self.genDigest()
            self.mtime_new = self.getMTime()
        self.digest = self.digest_new
        self.mtime = self.mtime_new
        self.isChanged = False
        
    def getMTime(self):
        return os.path.getmtime(self.f_path)
    
    def getDigest(self):
        return self.digest
    
    def genDigest(self):
        print('gen digest.')
        m = md5.new()
        f = open(self.f_path,'r')
        m.update(f.read())
        f.close()
        return m.hexdigest()

if __name__=='__main__':
    import sys
    if len(sys.argv)<2:
        print('usage:%s file'%sys.argv[0])
        exit()

    fdListenter = FileDiffListener(sys.argv[1])
    while 1:
        import time
        time.sleep(1)
        if fdListenter.isDiff() :
            print('changed: digest:%s'%fdListenter.getDigest())
            fdListenter.saveDiff()

